package log

import (
	"cm2/util"
	"path"

	"github.com/kataras/golog"
)

const sysReservedLoggerName = "__sys"

var loggers map[string]*golog.Logger

// Init 根据参数创建日志
func Init(config []interface{}) {
	if loggers == nil {
		initLoggerCollection()
	}

	// 创建默认日志，如果在config失败时

	for _, v := range config {
		conf := v.(map[string]interface{})
		ln := conf["name"].(string)
		ll := conf["level"].(string)
		lp := conf["path"].(string)

		createLogger(ln, ll, lp)
	}
}

// CreateReservedDefaultLogger 创建系统保留日志，无论如何都创建
func CreateReservedDefaultLogger() {
	if loggers == nil {
		initLoggerCollection()
	}

	createLogger(sysReservedLoggerName, "debug", "logs")
}

// DefaultLogger 默认日志记录器
func DefaultLogger() *golog.Logger {
	if loggers == nil {
		CreateReservedDefaultLogger()
	}

	var l *golog.Logger
	var ok bool
	// 取 default
	l, ok = loggers["default"]
	if !ok {
		l, _ = loggers[sysReservedLoggerName]
	}

	return l
}

// NamedLogger 已初始化的日志记录器
func NamedLogger(name string) *golog.Logger {
	if loggers == nil {
		return nil
	}

	return loggers[name]
}

func initLoggerCollection() {
	loggers = make(map[string]*golog.Logger)
}

func createLogger(lname, llevel, lpath string) {
	loggers[lname] = NewRotateLog(
		path.Join(util.GetWorkingPath(), lpath),
		lname,
		llevel,
		604800,
		86400,
	)
}
